package com.song.day01文件传输.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.DefaultFileRegion;
import io.netty.channel.FileRegion;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

import java.io.File;
import java.io.RandomAccessFile;

//SimpleChannelInboundHandler<PackageMessage>
public class ServerHandler  extends  ChannelInboundHandlerAdapter{

	private static final String CR = System.getProperty("line.separator");
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
			throws Exception {
		// TODO Auto-generated method stub
		super.userEventTriggered(ctx, evt);
		
		if( evt instanceof IdleStateEvent)
		{
			IdleStateEvent event = (IdleStateEvent) evt;
			if(event.state()  == IdleState.READER_IDLE)
			{
				System.out.println("---READER_IDLE---");
			}else if(event.state() == IdleState.WRITER_IDLE)
			{
				System.out.println("---WRITER_IDLE---");
			}
			
		}
		
	}

	
	
	public void channelRead(ChannelHandlerContext ctx, Object obj)
			throws Exception {
		
		String name = obj.toString();
		File file = new File(name);
		if(file.exists())
		{
			RandomAccessFile accessFile = new RandomAccessFile(name, "r");
			FileRegion region = new DefaultFileRegion(accessFile.getChannel(), 0, accessFile.length());
			ctx.writeAndFlush(region);
			ctx.writeAndFlush(CR);
			accessFile.close();
		}
		
		
	}


	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) {
		ctx.flush();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		System.out.println(cause.getCause());
		ctx.close();
	}


}
